import React, { createContext, useContext, useState, ReactNode, useCallback, useEffect } from 'react';
import VcodeCaptcha from '../components/VcodeCaptcha/VcodeCaptcha';

// 验证配置
export interface VerifyConfig {
  title?: string;
  description?: string;
  onSuccess?: (data?: any) => void;
  onFail?: (error?: any) => void;
  onClose?: () => void;
}

// Context 类型
interface VerifyContextType {
  showVerify: (config?: VerifyConfig) => Promise<boolean>;
  hideVerify: () => void;
  isVisible: boolean;
}

// 创建 Context
const VerifyContext = createContext<VerifyContextType | undefined>(undefined);

// Provider Props
interface VerifyProviderProps {
  children: ReactNode;
}

// Provider 组件
export const VerifyProvider: React.FC<VerifyProviderProps> = ({ children }) => {
  const [isVisible, setIsVisible] = useState(false);
  const [currentConfig, setCurrentConfig] = useState<VerifyConfig | null>(null);
  const [resolvePromise, setResolvePromise] = useState<((value: boolean) => void) | null>(null);

  // 显示验证码
  const showVerify = useCallback((config: VerifyConfig = {}): Promise<boolean> => {
    setCurrentConfig(config);
    setIsVisible(true);

    return new Promise<boolean>((resolve) => {
      setResolvePromise(() => resolve);
    });
  }, []);

  // 注册全局验证函数
  useEffect(() => {
    import('../utils/verifyHelper').then(({ setGlobalVerify }) => {
      setGlobalVerify(showVerify);
    });
  }, [showVerify]);

  // 隐藏验证码
  const hideVerify = () => {
    setIsVisible(false);
    setTimeout(() => {
      setCurrentConfig(null);
      if (resolvePromise) {
        resolvePromise(false);
        setResolvePromise(null);
      }
    }, 300);
  };

  // 验证成功回调
  const handleSuccess = (data: any) => {
    console.log('验证成功，数据:', data);
    currentConfig?.onSuccess?.(data);
    setIsVisible(false);
    
    setTimeout(() => {
      setCurrentConfig(null);
      if (resolvePromise) {
        resolvePromise(true);
        setResolvePromise(null);
      }
    }, 300);
  };

  // 验证失败回调
  const handleFail = (error: any) => {
    console.log('验证失败，错误:', error);
    currentConfig?.onFail?.(error);
  };

  // 关闭回调
  const handleClose = () => {
    currentConfig?.onClose?.();
    hideVerify();
  };

  const value: VerifyContextType = {
    showVerify,
    hideVerify,
    isVisible,
  };

  return (
    <VerifyContext.Provider value={value}>
      {children}
      {isVisible && (
        <VcodeCaptcha
          open={isVisible}
          onSuccess={handleSuccess}
          onFail={handleFail}
          onClose={handleClose}
          title={currentConfig?.title || '安全验证'}
          description={currentConfig?.description || '请输入图片中的验证码'}
        />
      )}
    </VerifyContext.Provider>
  );
};

// 自定义 Hook
export const useVerify = (): VerifyContextType => {
  const context = useContext(VerifyContext);
  if (context === undefined) {
    throw new Error('useVerify must be used within a VerifyProvider');
  }
  return context;
};
